<template>
    <div class="app-container">
        <el-form ref="searchForm" inline :model="searchForm" style="position:relative;margin-bottom:20px;">
            <el-row>
                <el-col :span="20">
                    <el-form-item label="应用程序：" prop="appId">
                        <el-select clearable v-model="searchForm.appId" placeholder="请选择" @change="searchChangeApp">
                            <el-option v-for="item in appIdOpt" :key="item.id" :label="item.name" :value="item.id"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="导航：" prop="navBarId">
                        <el-select clearable v-model="searchForm.navBarId" placeholder="请选择">
                            <el-option v-for="item in searchnavBarOpt" :key="item.id" :label="item.name" :value="item.id"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="所属菜单：" prop="id">
                        <el-cascader clearable :options="menuOpt" :props="optionProps" v-model="searchForm.id" change-on-select></el-cascader>
                    </el-form-item>
                    <el-form-item label="菜单名称：" prop="name">
                        <el-input clearable v-model="searchForm.name" placeholder="请输入"></el-input>
                    </el-form-item>
                    <el-form-item label="可见性：" prop="visibility">
                        <el-select clearable v-model="searchForm.visibility" placeholder="请选择">
                            <el-option v-for="item in visibilityOpt" :key="item.value" :label="item.label" :value="item.value"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-button @click="init('search')" type="primary">查询</el-button>
                </el-col>
                <el-col :span="4">
                    <el-button @click="addClick(1)" type="primary" style="position: absolute;right: 0;">添加导航菜单</el-button>
                </el-col>
            </el-row>
        </el-form>
        <el-table :data="tableData" style="width: 100%" border row-key="id" id="treeTable">
            <el-table-column type="index" label="序号" width="50" align="center"></el-table-column>
            <el-table-column prop="name" label="名称" width="180" align="center"></el-table-column>
            <el-table-column prop="appName" label="所属应用" align="center"></el-table-column>
            <el-table-column prop="navBarName" label="应用导航" align="center"></el-table-column>
            <el-table-column prop="url" label="链接地址" align="center"></el-table-column>
            <el-table-column prop="target" :formatter="targetFun" label="打开方式" align="center"></el-table-column>
            <el-table-column prop="sort" label="顺序值" align="center"></el-table-column>
            <el-table-column prop="visibility" :formatter="visibilityFun" label="可见性" align="center"></el-table-column>
            <el-table-column prop="createTime" label="创建时间" align="center" width="160"></el-table-column>
            <el-table-column label="操作" width="240" align="center" fixed="right">
                <template slot-scope="scope">
                    <el-button style="margin-bottom: 5px;" @click.stop="editClick(scope.row)" type="primary" plain :disabled="(scope.row.usingStatus != 1)" size="mini">编辑</el-button>
                    <el-button style="margin-bottom: 5px;" @click.stop="addClick(2,scope.row)" plain :disabled="(scope.row.usingStatus != 1)" size="mini">添加子菜单</el-button>
                    <el-button style="margin-bottom: 5px;" @click.stop="removeClick(scope.row)" type="warning" plain size="mini">移动到</el-button>
                    <el-button style="margin-bottom: 5px;" @click.stop="delClick(scope.row)" type="danger" plain size="mini">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-pagination @current-change="getList" layout="total, prev, pager, next, jumper" :total="pageData.totalElements"></el-pagination>
        <!-- 弹框 -->
        <el-dialog :visible.sync="showDialog" width="800px">
            <el-form ref="dataForm" :rules="rules" :model="dataForm" label-position="left" label-width="100px" style="margin: 0px 50px;">
                <el-form-item label="应用程序：" prop="applicationId">
                    <el-select v-model="dataForm.applicationId" placeholder="必选项。请选择" @change="changeApp" style="width: 100%">
                        <el-option v-for="item in appIdOpt" :key="item.id" :label="item.name" :value="item.id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="导航栏：" prop="navBarId">
                    <el-select v-model="dataForm.navBarId" placeholder="必选项。请选择" style="width: 100%">
                        <el-option v-for="item in navBarOpt" :key="item.id" :label="item.name" :value="item.id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="菜单名称：" prop="name">
                    <el-input v-model="dataForm.name" placeholder="必填项。请输入长度为1-30位由中英文数字-_.组成的名称" maxlength="30"></el-input>
                </el-form-item>
                <el-form-item label="所属栏目：" prop="columnId">
                    <el-cascader clearable :options="parentOpt" :props="optionProps" v-model="columnId" change-on-select style="width: 100%"></el-cascader>
                </el-form-item>
                <el-form-item label="默认图片：" prop="image">
                    <el-upload class="avatar-uploader" action="" :http-request="UploadImage" :show-file-list="false" :before-upload="beforeAvatarUpload" >
                        <img v-if="imageUrl" :src="imageUrl" class="avatar" width="100%">
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                </el-form-item>
                <el-form-item label="链接地址：" prop="url">
                    <el-input v-model="dataForm.url" placeholder="请输入链接地址"></el-input>
                </el-form-item>
                <el-form-item label="打开方式：" prop="target">
                    <el-select v-model="dataForm.target" placeholder="请选择" style="width: 100%">
                        <el-option v-for="item in openTypeOpt" :key="item.value" :label="item.label" :value="item.value"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="顺序值：" prop="sort">
                    <el-input v-model="dataForm.sort" type="number" placeholder="请输入顺序值"></el-input>
                </el-form-item>
                <el-form-item label="可见性：" prop="visibility">
                    <el-select v-model="dataForm.visibility" placeholder="请选择" style="width: 100%">
                        <el-option v-for="item in visibilityOpt" :key="item.value" :label="item.label" :value="item.value"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button @click="addSubmit('dataForm')" type="primary">保存</el-button>
                    <el-button @click="cancelClick('dataForm')">取消</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>
        <!-- 图片弹框 -->
        <el-dialog :visible.sync="showPicDialog" width="1000px">
            <img :src="nowPic" alt="" style="max-width: 100%;margin: 0 auto 15px;display: inherit" />
        </el-dialog>
        <!-- 弹框 -->
        <el-dialog :visible.sync="removeDialog">
            <el-form ref="removeForm" :model="removeForm" label-position="left" label-width="100px" style="margin: 0px 50px;">
                <el-form-item label="所属菜单：" prop="name">
                    <el-cascader clearable :options="menuOpt" :props="optionProps" v-model="removeForm.name" change-on-select style="width: 100%"></el-cascader>
                </el-form-item>
                <el-form-item>
                    <el-button @click="removeSubmit('removeForm')" type="primary">保存</el-button>
                    <el-button @click="cancelClick('removeForm')">取消</el-button>
                </el-form-item>
            </el-form>
        </el-dialog>
    </div>
</template>
<script>
import { findColumn, getDirColumn } from '@/api/content/column'
import { findApplication } from '@/api/application/application'
import { findNavBar } from '@/api/application/application-nav'
import { creatMenu, findMenu, updateMenu, removedMenu, getMenu, delMenu } from '@/api/application/application-menu'
import { uploadPic, getPic } from '@/api/uploadPic'
import { isNameValidate, isvalidInitNumber } from '@/utils/validate'
export default {
    name: 'NavMenu',
    data() {
        var NameValidate=(rule, value,callback)=>{
            if(isNameValidate(value)){
                callback()
            }else{
                callback(new Error('请输入长度为1-30位由中英文数字-_.组成的名称'))
            }
        }
        var InitNumber=(rule, value,callback)=>{
            if(value){
                if(isvalidInitNumber(value)){
                    callback()
                }else{
                    callback(new Error('请输入整数'))
                }
            }else{
                callback()
            }
        }
        return{
            tableData: [],
            nowTit: '',
            nowId: '',
            showDialog: false,
            dataForm: {
                image: '',
                name: '',
                columnId: '',
                navBarId: '',
                parentId: '',
                applicationId: '',
                sort: '',
                target: 1,
                url: '',
                visibility: 1,
                usingStatus: 1,
            },
            rules: {
                name: [
                    { required: true, message: '请输入菜单名称', trigger: 'blur' },
                    {  trigger: 'blur', validator: NameValidate }
                ],
                applicationId: [
                    { required: true, message: '请选择应用程序', trigger: 'change' }
                ],
                navBarId: [
                    { required: true, message: '请选择导航栏', trigger: 'change' }
                ],
                sort: [
                    { trigger: 'blur', validator: InitNumber }
                ],
            },
            searchForm:{
                id: [],
                appId: '',
                navBarId: '',
                name: '',
                usingStatus: '',
                visibility: '',
            },
            nowPage: 0,
            pageSize: 10,
            imageUrl: '',
            nowPic: '',
            formData: {},
            popStatus: 0,  //0为添加，1为修改
            pageData: {},
            usingStatusOpt: [
                {label: '启用', value: 1},
                {label: '禁用', value: 0}
            ],
            visibilityOpt: [
                {label: '显示', value: 1},
                {label: '隐藏', value: 2}
            ],
            openTypeOpt: [
                {label: '不打开', value: 1},
                {label: '当前窗口', value: 2},
                {label: '新窗口', value: 3}
            ],
            appIdOpt: [],
            showPicDialog: false,
            searchnavBarOpt: [],
            navBarOpt: [],
            menuOpt: [],
            removeDialog: false,
            removeForm: {
                name: [],
                id: ''
            },
            columnId: [],
            parentOpt: [],
            optionProps: {
                value: 'id',
                label: 'name',
                children: 'children'
            },
        }
    },
    methods: {
        //默认函数
        init(params){
            const _this = this;
            if(params == 'search'){
                _this.nowPage = 0
            }
            let cid = '';
            if(this.searchForm.id.length != 0){
                cid = this.searchForm.id[this.searchForm.id.length - 1];
            }
            _this.tableData = [];
            //获取列表信息
            findMenu(_this.nowPage, _this.pageSize, _this.searchForm.name, cid, _this.searchForm.appId, _this.searchForm.navBarId, _this.searchForm.usingStatus, _this.searchForm.visibility ).then(response => {
                if(response.code == 200){
                    _this.pageData = response.object
                    _this.tableData = response.object.content
                    // if(response.object.content){
                    //     for (const key in response.object.content) {
                    //         //处理图片
                    //         if(response.object.content[key].image){
                    //             getPic(response.object.content[key].image).then(res => {
                    //                 if(res.code == 200){
                    //                     response.object.content[key].showpic = res.object;
                    //                     _this.tableData.push(response.object.content[key]);
                    //                 }else{
                    //                     this.$message.error(res.message);
                    //                 }
                    //             })
                    //         }else{
                    //             response.object.content[key].showpic = '';
                    //             _this.tableData.push(response.object.content[key]);
                    //         }

                    //     }
                    // }
                }else{
                    this.$message.error(response.message);
                }
            })
        },
        //递归
        getTreeData(data){
            for(var i=0;i<data.length;i++){
                if(data[i].children.length<1){
                    data[i].children=undefined;
                }else {
                    this.getTreeData(data[i].children);
                }
            }
            return data;
        },
        columnOpt(){
            const _this = this;
            //获取列表信息
            findColumn( '', '', '', 0, 10000).then(response => {
                if(response.code == 200){
                    if(response.object){
                        if(response.object.content){
                            const arr = response.object.content;
                            _this.parentOpt = _this.getTreeData(arr);
                        }
                    }
                }else{
                    this.$message.error(response.message);
                }
            })
        },
        menuList(){
            const _this = this;
            //获取列表信息
            findMenu(0, 10000, '', '', '', '', '', '' ).then(response => {
                if(response.code == 200){
                    const arr = response.object.content;
                    _this.menuOpt = _this.getTreeData(arr);
                }else{
                    this.$message.error(response.message);
                }
            })
        },
        applicationList(){
            const _this = this;
            //获取列表信息
            findApplication({ page: 0, size: 10000, name: '' }).then(response => {
                if(response.code == 200){
                    _this.appIdOpt = response.object.content;
                }else{
                    this.$message.error(response.message);
                }
            })
        },
        navBarList(appId,type){
            const _this = this;
            //获取列表信息
            findNavBar( 0, 10000, '', appId ).then(response => {
                if(response.code == 200){
                    if(type == 1){
                        _this.searchnavBarOpt = response.object.content;
                    }else if(type == 2){
                        _this.navBarOpt = response.object.content;
                    }
                }else{
                    this.$message.error(response.message);
                }
            })
        },
        //添加
        addClick(type,row){
            this.popStatus = 0;
            this.showDialog = true;
            //父级栏目id
            if(type == 1){
                this.dataForm.parentId = '0';
            }else if(type == 2){
                this.dataForm.parentId = row.id;
            }
            this.dataForm.applicationId = '';
            this.dataForm.image = '';
            this.dataForm.name = '';
            this.columnId = [];
            this.dataForm.columnId = '';
            this.dataForm.navBarId = '';
            this.dataForm.sort = '';
            this.dataForm.target = 1;
            this.dataForm.url = '';
            this.dataForm.visibility = 1;
            this.dataForm.usingStatus = 1;
            this.imageUrl = '';
            if(this.dataForm.id){
                delete this.dataForm.id;
            }
        },
        //提交添加
        addSubmit(formName){
            let _this = this;
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    //提交
                    _this.dataForm.columnId = this.columnId[this.columnId.length - 1];
                    if(_this.popStatus == 0){  //添加
                        creatMenu(_this.dataForm).then(response => {
                            if(response.code == 200){
                                this.$message.success(response.message);
                                _this.init();
                                _this.menuList();
                                _this.showDialog = false;
                            }else{
                                this.$message.error(response.message);
                            }
                        })
                    }else if(_this.popStatus == 1){  //修改
                        _this.dataForm.id = _this.nowId;
                        updateMenu(_this.dataForm).then(response => {
                            if(response.code == 200){
                                this.$message.success(response.message);
                                _this.init();
                                _this.menuList();
                                _this.showDialog = false;
                            }else{
                                this.$message.error(response.message);
                            }
                        })
                    }
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        //删
        delClick(row){
            let _this = this;
            this.$confirm('确定删除 '+row.name+' 吗?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                //删除
                delMenu(row.id).then(response => {
                    if(response.code == 200){
                        this.$message.success(response.message);
                        _this.init();
                    }else{
                        this.$message.error(response.message);
                    }
                })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消'
                });          
            });
        },
        //编辑
        editClick(row){
            this.popStatus = 1;
            this.nowId = row.id;
            getMenu( this.nowId ).then(response => {
                if(response.code == 200){
                    this.dataForm.applicationId = response.object.applicationId;
                    this.dataForm.image = response.object.image;
                    this.dataForm.name = response.object.name;
                    this.dataForm.columnId = response.object.columnId;
                    this.navBarList(response.object.applicationId,2);
                    this.dataForm.navBarId = response.object.navBarId;
                    this.dataForm.sort = response.object.sort;
                    this.dataForm.target = response.object.target;
                    this.dataForm.url = response.object.url;
                    this.dataForm.parentId = response.object.parentId;
                    this.dataForm.visibility = response.object.visibility;
                    this.dataForm.usingStatus = response.object.usingStatus;
                    // if(response.object.image){
                    //     this.imageUrl = response.object.showpic;
                    // }else{
                    //     this.imageUrl = '';
                    // }
                    this.imageUrl = response.object.image
                    //处理所属项目id
                    if(response.object.parentList){
                        let arr = [];
                        for (const key in response.object.parentList) {
                            if (response.object.parentList.hasOwnProperty(key)) {
                                const element = response.object.parentList[key];
                                arr.push(element.id);
                            }
                        }
                        this.columnId = arr;
                    }
                    this.showDialog = true;
                }else{
                    this.$message.error(response.message);
                }
            })
        },
        //取消
        cancelClick(formName){
            this.showDialog = false;
            this.removeDialog = false
            this.$refs[formName].resetFields();
        },
        //移动到
        removeClick(row){
            this.removeForm.id = row.id;
            this.removeForm.name = [];
            this.removeDialog = true;
        },
        removeSubmit(){
            const _this = this;
            if(this.removeForm.name.length == 0){
                this.$message.info('请选择需要移动到的栏目');
            }else{
                removedMenu({sourceId: this.removeForm.id, targetId: this.removeForm.name[this.removeForm.name.length - 1]}).then(response => {
                    if(response.code == 200){
                        this.$message.success(response.message);
                        _this.init();
                        _this.columnOpt();
                        _this.removeDialog = false;
                    }else{
                        this.$message.error(response.message);
                    }
                })
            }
        },
        //自定义上传
        UploadImage(param){
            const _this = this;
            //获取所属栏目的存储位置
            if(_this.columnId.length != 0){
                getDirColumn(_this.columnId[_this.columnId.length - 1]).then(response => {
                    if(response.code == 200){
                        //上传图片
                        let formData = new FormData();
                        formData.append('photoFile', param.file);
                        formData.append('dir', response.object);
                        formData.append('fileType', '1');
                        uploadPic(formData).then(response => {
                            if(response.code == 200){
                                _this.dataForm.image = response.object.saveImage;
                                this.imageUrl = response.object.showImage;
                            }else{
                                this.$message.error(response.message);
                            }
                        })
                    }else{
                        this.$message.error(response.message);
                    }
                })
            }else{
                this.$message.warning('请先选择所属栏目');
            }
        },
        //准备上传
        beforeAvatarUpload(file){
            const isJPG = file.type;
            const isLt2M = file.size / 1024 / 1024 < 4;
            if(((isJPG === 'image/jpeg') || (isJPG === 'image/png') || (isJPG === 'image/jpg') || (isJPG === 'image/gif') || (isJPG === 'image/JPEG') || (isJPG === 'image/PNG') || (isJPG === 'image/JPG') || (isJPG === 'image/GIF')) == false){
                this.$message.error('上传图片只能是 jpeg、png、jpg、gif 格式!');
            }
            if (!isLt2M) {
                this.$message.error('上传图片大小不能超过 4MB!');
            }
            return isJPG && isLt2M;
        },
        //放大图片
        enlargeFun(pic){
            this.showPicDialog = true;
            this.nowPic = pic;
        },
        //分页
        getList(val) {
            this.nowPage = val - 1;
            this.init();
        },
        usingStatusFun(row){
            if(row.usingStatus == 1){
                return '启用'
            }else if(row.usingStatus == 0){
                return '禁用'
            }
        },
        visibilityFun(row){
            if(row.visibility == 1){
                return '显示'
            }else if(row.visibility == 2){
                return '隐藏'
            }
        },
        targetFun(row){
            if(row.target == 1){
                return '不打开'
            }else if(row.target == 2){
                return '当前窗口'
            }else if(row.target == 3){
                return '新窗口'
            }
        },
        searchChangeApp(val){
            this.searchForm.navBarId = '';
            this.navBarList(val,1);
        },
        changeApp(val){
            this.dataForm.navBarId = '';
            this.navBarList(val,2);
        },
    },
    mounted(){
        this.init();
        this.applicationList();
        this.menuList();
        this.columnOpt();
    }
}
</script>
<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
<style>
    #treeTable .el-icon-arrow-right:before{
        color: #2196f3;
        font-weight: bold;
        /* content: "\E6DC"; */
        content: "\E791";
    }
    #treeTable .el-table__row,#treeTable .el-table__row.el-table__row--level-0{
        background: #e8f4ff;
    }
    #treeTable .el-table__row.el-table__row--level-1{
        background: #f0f9eb;
    }
    #treeTable .el-table__row.el-table__row--level-2{
        background: oldlace;
    }
    #treeTable tr.hover-row > td{
        background-color: initial;
    }
    #treeTable.el-table th > .cell{
        text-align: center;
    }
</style>